<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <el-form ref="queryForm" :model="queryParams" :inline="true">
          <el-form-item label="适用地区" prop="province">
            <el-select
              v-model="queryParams.province"
              remote
              filterable
              placeholder="请选择地区"
              :remote-method="remoteMethod"
              :loading="selectload"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in cityList"
                :key="index"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb10" style="float:right">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">
              <span>新增</span>
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
        </el-row>

        <el-table
          v-loading="loading"
          :data="courseList"
          border
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChang"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="编码" sortable="custom" width="75" type="index" />
          <el-table-column label="科目名称" prop="name" :show-overflow-tooltip="true" />
          <el-table-column label="所属地区" prop="province" :show-overflow-tooltip="true" />
          <el-table-column label="操作" class-name="small-padding fixed-width" width="120">
            <template slot-scope="scope">
              <!-- <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                :disabled="!multiple && single"
                @click="handleUpdate(scope.row)"
              >修改</el-button> -->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改对话框 -->
        <el-drawer
          ref="drawer"
          :title="title"
          :visible.sync="open"
          direction="rtl"
          custom-class="demo-drawer"
        >
          <div class="demo-drawer__content">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
              <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入" />
              </el-form-item>
              <el-form-item label="适用地区" prop="province">
                <el-select
                  v-model="form.province"
                  remote
                  filterable
                  placeholder="请选择地区"
                  :remote-method="remoteMethod"
                  :loading="selectload"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in cityList"
                    :key="index"
                    :label="item.name"
                    :value="item.name"
                  />
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="知识点">
                <el-tag
                  v-for="(tag,index) in knowledge_points"
                  :key="index"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag, index)"
                >{{ tag.name }}</el-tag>
                <el-input
                  v-if="inputVisible"
                  ref="saveTagInput"
                  v-model="inputValue"
                  class="input-new-tag"
                  size="small"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm"
                />
                <el-button
                  v-else
                  icon="el-icon-plus"
                  class="button-new-tag"
                  size="small"
                  @click="showInput"
                >新增</el-button>
              </el-form-item> -->
            </el-form>
            <div class="demo-drawer__footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </div>
        </el-drawer>
      </el-card>
    </template>
  </BasicLayout>
</template>

<script>
import {
  getSubject,
  addSubject,
  getSubjectDetails,
  delKnowledgePoint,
  delSubject,
  addKnowledgePoint
} from '@/api/admin/sys-subject'
import { getCity } from '@/api/admin/sys-course'
export default {
  name: 'SysAcademy',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      chooseIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 表格数据
      courseList: [],
      // 排序字段
      order: 'createdAtOrder',
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        province: undefined
      },
      form: {},
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        province: [{ required: true, message: '选择适用地区', trigger: 'blur' }]
      },
      knowledge_points: [],
      inputVisible: false,
      inputValue: '',
      selectId: null,
      cityList: [],
      selectload: false
    }
  },

  created() {
    this.getList()
    this.getCity()
  },
  methods: {
    getCity() {
      getCity().then(res => {
        this.cityList = res?.data || []
      })
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true
      getSubject(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          this.courseList = response.data
          this.loading = false
        }
      )
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
      this.getCity()
    },
    handleSortChang(column, prop, order) {
      prop = column.prop
      order = column.order
      if (this.order !== '' && this.order !== prop + 'Order') {
        this.queryParams[this.order] = undefined
      }
      if (order === 'descending') {
        this.queryParams[prop + 'Order'] = 'desc'
        this.order = prop + 'Order'
      } else if (order === 'ascending') {
        this.queryParams[prop + 'Order'] = 'asc'
        this.order = prop + 'Order'
      } else {
        this.queryParams[prop + 'Order'] = undefined
      }
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.chooseIds = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = (row.id && [row.id]) || this.chooseIds
      this.$confirm('是否确认删除', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return delSubject({ ids })
        })
        .then(response => {
          if (response.code === 200) {
            this.msgSuccess(response.msg)
            this.getList()
          } else {
            this.msgError(response.msg)
          }
        })
        .catch(function() {})
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加科目'
      this.getCity()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getCity()
      this.reset()
      this.form = JSON.parse(JSON.stringify(row))
      this.open = true
      this.title = '修改科目'
      this.selectId = row.id
      getSubjectDetails(row.id).then(res => {
        this.knowledge_points = res.data.knowledge_point
      })
    },
    // 表单重置
    reset() {
      this.form = {}
      this.knowledge_points = []
      this.resetForm('form')
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id) {
            this.open = false
            this.getList()
            return
          }
          addSubject({
            ...this.form,
            knowledge_points: this.knowledge_points
          }).then(res => {
            if (res.code === 200) {
              this.msgSuccess(res.msg)
              this.open = false
              this.getList()
            } else {
              this.msgError(res.msg)
            }
          })
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    handleClose(tag, index) {
      if (tag.id) {
        delKnowledgePoint(tag.id).then(res => {
          if (res.code === 200) {
            this.msgSuccess(res.msg)
          } else {
            this.msgError(res.msg)
          }
        })
      }
      this.knowledge_points.splice(index, 1)
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        if (this.selectId) {
          addKnowledgePoint({
            subject_id: this.selectId,
            knowledge_point: inputValue
          }).then(res => {
            this.knowledge_points.push({
              name: inputValue,
              subject_id: this.selectId,
              id: res.data
            })
          })
          this.inputVisible = false
          this.inputValue = ''
          return
        }
        this.knowledge_points.push({ name: inputValue })
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    remoteMethod(query) {
      if (query !== '') {
        this.selectload = true
        getCity({ name: query }).then(res => {
          this.cityList = res?.data || []
          this.selectload = false
        })
      } else {
        this.cityList = []
      }
    }
  }
}
</script>

<style>
.el-tag {
  margin-right: 5px;
}
.button-new-tag {
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  vertical-align: bottom;
}
</style>
